package com.meichuang.meipian.video;

import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import android.os.Environment;

import com.meichuang.meipian.video.nativejni.VideoNative;
import com.meichuang.meipian.video.util.FileUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

/**
 * Created by ken on 17/11/5.
 */

public class ZZGLRender implements GLSurfaceView.Renderer {
    static long jni_handler = -1;
    VideoNative mNative = new VideoNative();
    VideoNative.NativeCallBack mCallBack;
    public boolean isEnd = false;
    int width;
    int height;
    int frame_rate;
    int gadTimeSmall = 30;
    int renderModel = 0;
    int totalFrames;
    public boolean isClearShuiying = true;
    public interface OpenGLRenderEvent{
        public abstract void run();
    }
    List<OpenGLRenderEvent> eventList = new ArrayList<OpenGLRenderEvent>();
    public void setNativeCallBack(VideoNative.NativeCallBack callBack){
        mNative.setNativeCallBack(callBack);
        this.mCallBack = callBack;
    }

    public static final int RENDER_MODEL_RENDER = 0;
    public static final int RENDER_MODEL_RECORD = 1;
    public static final String app_root_path = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + ".meichuang" + File.separator;

    public static final String MultiSceneTemplateROOT = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + ".meichuang" + File.separator + "multiSceneTempLate" + File.separator;
    public static final String MultiSceneSceneROOT = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + ".meichuang" + File.separator + "scene" + File.separator;
    public static final String _multiSceneRootROOT = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + ".meichuang" + File.separator;//场景和场景组的最跟目录
    public static final String _cutVideoRoot = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + ".jianying/trimmedVideo";

    public static final String _centerMusicPath = _multiSceneRootROOT+"mypcm.aac";

    public static final String shuiyingFilePath = _multiSceneRootROOT+"jianying.shuiying";
    public static final String morenFilePath = _multiSceneRootROOT+"moren.jpg";
    public static final String outputCenterMp3FromVideo = _multiSceneRootROOT+"videotomp3center.aac";
    //    public static final String outputCenterMp3Fromm4a = _multiSceneRootROOT+"videotomp3centerfromm4a.mp3";
    public static final String outputCenterMp3Fromcut = _multiSceneRootROOT+"videotomp3centercut.aac";
    public void addRenderEvent(OpenGLRenderEvent event){
        this.eventList.add(event);
    }
    @Override
    public void onSurfaceCreated(GL10 gl, EGLConfig config){
    }

    @Override
    public void onSurfaceChanged(GL10 gl, int width, int height){
        this.width = width;
        this.height = height;
    }
    public void setFrameRateAndRenderModel(int frame,int type,int totalFrames){
        this.frame_rate = frame;
        gadTimeSmall = 1000/frame_rate;
        this.renderModel = type;
        this.totalFrames = totalFrames;
    }
    //    public void setRenderModel(int type){
//        this.renderModel = type;
//    }
    public void setUserConfig(final String json){
        isEnd = true;
        addRenderEvent(new OpenGLRenderEvent() {
            @Override
            public void run() {
                if(jni_handler != -1){
                    ZZGLRender.this.distoryRender();
                }
                if(jni_handler == -1){
                    jni_handler = mNative.getInstance();

                    mNative.setRenderModelAndFrame(jni_handler,renderModel,frame_rate,totalFrames,_centerMusicPath);
//                    my_mainBundleResourcePathROOT = mainBundleResourcePathROOT;
//                    my_currentSceneGroupUserResourcePathROOT = currentSceneGroupUserResourcePathROOT;
//                    my_multiSceneRootROOT=multiSceneRootROOT;
//                    my_multiSceneSceneROOT=multiSceneSceneROOT;
//                    my_multiSceneUserResourcesROOT=multiSceneUserResourcesROOT;
//                    my_multiSceneTemplateROOT=multiSceneTemplateROOT;
//                    my_assetsPath = assetsPath;

                    //1 字体 水印文件目录 和3一样
                    //2 用户切的图片的文件夹 直接使用全量路径
                    //3 场景 单场景和多场景的共同上层目录
                    //4 单场景文件夹
                    //5 用户切的图片的文件夹 和2一样
                    //6 场景组的文件夹目录
                    //7 assetsPath 目前没有用
                    mNative.setPathList(jni_handler,
                            _multiSceneRootROOT,MultiSceneSceneROOT,_multiSceneRootROOT,
                            MultiSceneSceneROOT,MultiSceneSceneROOT,MultiSceneTemplateROOT,
                            shuiyingFilePath,isClearShuiying);
                    mNative.initGLView(jni_handler,width,height);

                    isEnd = false;
                }
            }
        });

    }

    public static final int VIDEO_SPEED_ADJUST = 1;
    public static final int COLOR_ADJUST = 2;
    public static final int FILTER_ADJST = 3;
    public static final int ALPHA_ADJST = 4;
    public static final int HUNHE_ADJST = 5;
    public static final int MENGBAN_ADJST = 6;
    public static final int CLEAR_COLOR = 7;
    public static final int BEAUTY_ADJUST = 8;
    public static final int AUDIOMIXVOLUME_ADJUST = 9;
    public static final int AUDIO_SPEAD_ADJUST = 10;

    float read = 0;
    long oldTime = System.currentTimeMillis();
    @Override
    public void onDrawFrame(GL10 gl){

//        LogUtil.i("onDrawFrame start ");
        if(renderModel == RENDER_MODEL_RENDER){//如果是预览渲染
            long thisTime = System.currentTimeMillis();
            while(thisTime - oldTime < gadTimeSmall){
                try {
                    Thread.sleep(gadTimeSmall - (thisTime - oldTime ));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                thisTime = System.currentTimeMillis();
            }
            oldTime = thisTime;
        }

//        read+=0.02f;
//        if(read>1.0){
//            read = 0;
//        }
        List<OpenGLRenderEvent> mList = new ArrayList<>(eventList);
        for(OpenGLRenderEvent event:mList){
            event.run();
        }
        eventList.removeAll(mList);
        if(isEnd){
//            LogUtil.i("onDrawFrame end 1 ");
            return;
        }
        if(jni_handler != -1){
//            GLES20.glClearColor(255,0,0,1);
//            GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT | GLES20.GL_DEPTH_BUFFER_BIT);
            GLES20.glEnable(GLES20.GL_BLEND);
            GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA,GLES20.GL_ONE_MINUS_SRC_ALPHA);
            //long ts=System.currentTimeMillis();
            mNative.updateRender(jni_handler);
//            LogUtil.w("videoEngine"," "+mNative.getRenderFram(jni_handler));
            if(mCallBack != null){
                mCallBack.updateRender(mNative.getRenderFram(jni_handler));
            }
//            LogUtil.w("gadTime = "+(System.currentTimeMillis() - ts)+" ms");
        }else{
//            GLES20.glClearColor(0,0,0,1);
        }
//        LogUtil.i("onDrawFrame end 2 ");
    }

    public void encodeMusic(String path){
        mNative.encodeMP3(path);
    }

    public void distoryRender(){
        if(jni_handler !=-1){
            mNative.deleteRender(jni_handler);
            jni_handler=-1;
        }

    }











    //这部分到时候需要新增加别的方法从外面调用进来
    public void loadSceneGrop()
    {
        ZZGLRender _sceneMananger = this;

//        ifstream ifs;
//        ifs.open([sceneGropPath cStringUsingEncoding: NSUTF8StringEncoding]);
//        Json::Reader jsonReader;
//        Json::Value jsonRoot;
//        jsonRoot.clear();
//        jsonReader.parse(ifs, jsonRoot);

        String str = FileUtil.readSDFile("sdcard/jsoninfo.json");
        JSONArray infoArray;
        try{
            JSONObject jsonRoot = new JSONObject(str);
            infoArray =jsonRoot.getJSONArray("info");
            JSONObject  creatScene =  infoArray.getJSONObject(0);
//            creatScene.put("sceneJsonPath","sdcard/.jianying/scene/k5ca88vexy7r7f4pq447_174_zaoan/k5ca88vexy7r7f4pq447_174_zaoan.json");
//            creatScene.put("sId","52");
//            creatScene.put("sceneResourceFolderPath","sdcard");
//            creatScene.put("mainSceneId",0);


            String creatSceneStr = creatScene.toString();

            long _currentSceneId =  mNative.creatScene(jni_handler,creatSceneStr);

            mNative.setCutStatus(jni_handler,true);

//            mNative.seekFramaTime(jni_handler,20);

            String updateBackgroundstr = infoArray.getJSONObject(1).toString();

            mNative.updateBackground(jni_handler,_currentSceneId,updateBackgroundstr);


            infoArray.getJSONObject(3).getJSONObject("Info").put("videoFilePath","sdcard/abcd.mp4");



//            String videostr = infoArray.getJSONObject(3).toString();
//
////            long videoId = mNative.createVideo(jni_handler,videostr);
//
//            String animVideo =infoArray.getJSONObject(5).toString();
////            mNative.updateVideoAnim(jni_handler,videoId, animVideo);
//
//            String filterStr = infoArray.getJSONObject(6).toString();
//
////            mNative.updateVideoEffectAnim(jni_handler,videoId, VIDEO_SPEED_ADJUST, filterStr);
////
////            mNative.updateVideoEffectAnim(jni_handler,videoId, VIDEO_SPEED_ADJUST, filterStr);
//
//            filterStr = infoArray.getJSONObject(8).toString();
////            mNative.updateVideoEffectAnim(jni_handler,videoId, FILTER_ADJST, filterStr);
//
//            infoArray.getJSONObject(2).getJSONObject("Info").put("audioFilePath","sdcard/bg_audio.mp3");
//            String musicStr = infoArray.getJSONObject(2).toString();
//            long musicId =  mNative.createMusic(jni_handler,musicStr);
//
//
//
//            String audioMax = infoArray.getJSONObject(12).toString();
//
//            mNative.updateMusicEffectAnim(jni_handler,musicId,AUDIOMIXVOLUME_ADJUST,audioMax);
//
////            mNative.updateVideoEffectAnim(jni_handler,videoId, AUDIOMIXVOLUME_ADJUST, audioMax);
//
//            String audioSpead =  infoArray.getJSONObject(13).toString();
//
//            mNative.updateMusicEffectAnim(jni_handler,musicId,AUDIO_SPEAD_ADJUST,audioMax);
//
////            mNative.updateVideoEffectAnim(jni_handler,videoId, AUDIO_SPEAD_ADJUST, audioMax);
//
//            String textStr = infoArray.getJSONObject(14).toString();
//
//            long textId =  mNative.createText(jni_handler,textStr);


//            filterStr = infoArray.getJSONObject(8).toString();
//            mNative.updateVideoEffect(jni_handler,videoId, FILTER_ADJST, filterStr);

//            filterStr = infoArray.getJSONObject(9).toString();
//            mNative.updateTextEffect(jni_handler,textId, FILTER_ADJST, filterStr);


//            string mengban =  jsonRoot["info"][11].toStyledString();
//            _sceneMananger->updateVideoEffect(videoId, MENGBAN_ADJST, mengban);

//            filterStr = infoArray.getJSONObject(11).toString();
//            mNative.updateVideoEffect(jni_handler,videoId, MENGBAN_ADJST, filterStr);


        }catch (Exception e){
            e.printStackTrace();
        }

    }








}
